import React, { useEffect, useRef, useState, useMemo } from "react";
import "./Iframe.css";

function Iframe() {
    const sectionRefs = [useRef(null), useRef(null), useRef(null)];
    const [activeIndex, setActiveIndex] = useState(null);
    const [section1Ratio, setSection1Ratio] = useState(1);
    // 动画阶段控制
    const [initPhase, setInitPhase] = useState('waiting'); // 'waiting' | 'cube-growing' | 'iframe-growing' | 'done'
    const [shrinkPhase, setShrinkPhase] = useState('done'); // 'iframe-shrinking' | 'cube-shrinking' | 'done'
    // const [showCube, setShowCube] = useState(true); // 不再需要
    const cubeRef = useRef(null);
    const iframeRef = useRef(null);

    // 用 Intersection Observer 监听每个 section 的可见性，准确设置 activeIndex
    useEffect(() => {
        const observers = [];
        sectionRefs.forEach((ref, idx) => {
            if (!ref.current) return;
            const observer = new window.IntersectionObserver(
                ([entry]) => {
                    if (entry.intersectionRatio > 0.6) {
                        setActiveIndex(idx);
                    }
                },
                { threshold: [0.6] }
            );
            observer.observe(ref.current);
            observers.push(observer);
        });
        return () => observers.forEach(o => o.disconnect());
    }, [sectionRefs]);

    // 保留 section-1 ratio 监听用于旋转动画
    useEffect(() => {
        const section1 = sectionRefs[0].current;
        if (!section1) return;
        const observer = new window.IntersectionObserver(
            ([entry]) => {
                setSection1Ratio(entry.intersectionRatio);
            },
            { threshold: Array.from({ length: 101 }, (_, i) => i / 100) }
        );
        observer.observe(section1);
        return () => observer.disconnect();
    }, [sectionRefs[0]]);

    // 初始化动画
    useEffect(() => {
        if (initPhase === 'waiting') {
            setInitPhase('cube-growing');
        }
        if (initPhase === 'cube-growing') {
            setInitPhase('iframe-growing');
        }
        // 不再隐藏正方体
        // if (initPhase === 'iframe-growing') {
        //     const timer = setTimeout(() => {
        //         setInitPhase('done');
        //         setShowCube(false);
        //     }, 1200);
        //     return () => clearTimeout(timer);
        // }
    }, [initPhase]);

    // 切换到下一屏时的分阶段缩小动画（仅在初始化动画完成后才允许）
    useEffect(() => {
        if (initPhase !== 'done') return; // 初始化动画未完成不触发
        if (activeIndex !== 0 && shrinkPhase === 'done') {
            // setShowCube(true); // 先显示cube
            setShrinkPhase('iframe-shrinking');
        }
        if (activeIndex === 0 && shrinkPhase !== 'done') {
            setShrinkPhase('done');
            // setShowCube(false);
        }
    }, [activeIndex, initPhase, shrinkPhase]);

    // iframe缩小时，动画结束后再缩cube
    useEffect(() => {
        if (shrinkPhase === 'iframe-shrinking' && iframeRef.current) {
            const handle = () => setShrinkPhase('cube-shrinking');
            const node = iframeRef.current;
            node.addEventListener('transitionend', handle);
            return () => node.removeEventListener('transitionend', handle);
        }
    }, [shrinkPhase]);

    // cube缩小时，动画结束后隐藏cube
    useEffect(() => {
        if (shrinkPhase === 'cube-shrinking' && cubeRef.current) {
            const handle = () => {
                // setShowCube(false);
                setShrinkPhase('done');
            };
            const node = cubeRef.current;
            node.addEventListener('transitionend', handle);
            return () => node.removeEventListener('transitionend', handle);
        }
    }, [shrinkPhase]);

    // scale逻辑
    let cubeScale = 1, iframeScale = 1;
    if (initPhase === 'waiting') {
        cubeScale = 0.2;
        iframeScale = 0.2;
    } else if (initPhase === 'cube-growing') {
        cubeScale = 0.2;
        iframeScale = 0.2;
    } else if (initPhase === 'iframe-growing') {
        cubeScale = 1;
        iframeScale = 0.2;
    } else if (initPhase === 'done' && activeIndex === 0) {
        cubeScale = 1;
        iframeScale = 1;
    } else if (shrinkPhase === 'iframe-shrinking') {
        cubeScale = 1;
        iframeScale = 0.2;
    } else if (shrinkPhase === 'cube-shrinking') {
        cubeScale = 0.2;
        iframeScale = 0.2;
    } else if (activeIndex !== 0) {
        cubeScale = 0.2;
        iframeScale = 0.2;
    }

    const baseWidth = '100vw';
    const baseHeight = '100vh';

    // 计算cube-border的旋转角度，scale越小旋转越大
    const rotateX = 24 + (1 - cubeScale) * 20; // 24~44度
    const rotateY = 18 + (1 - cubeScale) * 15; // 18~33度

    // 计算宽高，section-1时为100vw/100vh，离开时为300x300
    const iframeWidth = useMemo(() => (activeIndex === 0) ? '100vw' : '300px', [activeIndex]);
    const iframeHeight = useMemo(() => (activeIndex === 0) ? '100vh' : '300px', [activeIndex]);

    return (
        <div className="home-container">
            {activeIndex}activeIndex
            <div
                className={`section section-1`}
                ref={sectionRefs[0]}
            >
                {/* <div className="cube-bg"></div> */}
                <div className="iframe-wrapper">
                    <div
                        ref={cubeRef}
                        className="cube-cube"
                        style={{
                            width: baseWidth,
                            height: baseHeight,
                            transform: `translate(-50%, -50%) scale(${cubeScale}) rotateX(${rotateX}deg) rotateY(${rotateY}deg)`,
                            transition: 'transform 1.2s cubic-bezier(.4,2,.6,1)',
                        }}
                    >
                        <div className="cube-face cube-face-front" style={{width: baseWidth, height: baseHeight}}></div>
                        <div className="cube-face cube-face-back" style={{width: baseWidth, height: baseHeight}}></div>
                        <div className="cube-face cube-face-right" style={{width: baseWidth, height: baseHeight}}></div>
                        <div className="cube-face cube-face-left" style={{width: baseWidth, height: baseHeight}}></div>
                        <div className="cube-face cube-face-top" style={{width: baseWidth, height: baseHeight}}></div>
                        <div className="cube-face cube-face-bottom" style={{width: baseWidth, height: baseHeight}}></div>
                    </div>
                    <iframe
                        ref={iframeRef}
                        src='https://my.spline.design/particlescopy-XF8HDy46GDUoB22bFr1HlDqH/'
                        frameBorder='0'
                        style={{
                            width: baseWidth,
                            height: baseHeight,
                            transform: `translate(-50%, -50%) scale(${iframeScale})`,
                            transition: 'transform 1.2s cubic-bezier(.4,2,.6,1)',
                        }}
                    ></iframe>
                </div>
            </div>
            <div className={`section section-2${activeIndex === 1 ? "" : " shrink"}`} ref={sectionRefs[1]}>
            </div>
            <div className={`section section-3${activeIndex === 2 ? "" : " shrink"}`} ref={sectionRefs[2]}>
            </div>
        </div>
    );
}

export default Iframe;

